var common = require("../../../common/common.js").common;

const app = getApp();

var util = require("../../../utils/util.js");

Page({
    /**
   * 页面的初始数据
   */
    data: {
        lottery_prize_id: "",
        items: "",
        integal_use: true,
        voucher_use: true,
        voucher_id: "",
        chose_delivery_channel: null,
        payment_channel: 1,
        goodsListStyle: {
            style: 2,
            screenFull: false,
            styleConfig: {
                backgroundColor: "#fff"
            }
        },
        discount_label: 1,
        //选择可使用红包
        confirm_lead: 0,
        //团长确认弹框
        defferNum: "立即支付",
        //
        payWayList: [],
        payWayList1: [ {
            iconfonts: "icon-yue",
            //支付方式icon
            payWayName: "余额",
            //支付方式名称pay
            id: 2,
            color: "#FFAE00",
            //icon颜色,
            isDisabled: false,
            //是否禁用
            isShow: true
        }, {
            iconfonts: "icon-weixinzhifu",
            payWayName: "微信支付",
            id: 1,
            color: "#45C144",
            isDisabled: false,
            isShow: true
        }, {
            //专项资金
            iconfonts: "icon-zijin",
            payWayName: "专项资金",
            id: 3,
            color: "#ff3d17",
            isDisabled: false,
            isShow: true
        }, {
            iconfonts: "icon-huowu",
            payWayName: "货到付款",
            id: 4,
            color: "#608aff",
            isDisabled: false,
            isShow: true
        } ],
        componentStyle: {
            navigationTitle: "立即支付",
            goBack: 2
        },
        actually_paid: 0,
        hidden_discount: 0,
        payButtonDisabled: false,
        subscribeMessage: true,
        delivery_rangeArr: 0,
        reach_time: "",
        multiIndex: [ 0, 0 ],
        delivery_rangeArr: [],
        user_est_time: "",
        come: 0
    },
    //获取去右侧胶囊的信息
    getHeader() {
        let menuRect = wx.getMenuButtonBoundingClientRect();
        this.setData({
            topBarHeight: menuRect.height,
            topBarTop: menuRect.top
        });
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        this.getHeader();
        var _this = this;
        _this.setData({
            isIPX: app.globalData.isIPX || "",
            seckill_session_id: options.time_id || "",
            //接秒杀活动id
            group_solit_id: options.group_id || "",
            //接龙活动id
            status: options.status,
            operation: options.operation ? options.operation : 0,
            //3拼团下单，0其他 
            operation_type: options.operation_type || 0,
            //1拼团购买 0单独购买
            proceed_id: options.proceed_id || "",
            //所参加的正在进行的拼团id
            options: options,
            come: options.come || 0
        });
        if (options.sku_item) {
            var sku_item = options.sku_item.split("|");
            var items = [];
            sku_item.forEach((item, index) => {
                var item = item.split(",");
                items.push({
                    sku_id: item[0],
                    num: item[1]
                });
            });
            _this.setData({
                items: items
            });
        }
        if (options.lottery_prize_id) {
            this.setData({
                lottery_prize_id: options.lottery_prize_id
            });
        }
        _this.getInfo();
        _this.getBase();
        var P1 = _this.getMyLeaderInfo();
        var P2 = _this.getRecieverInfo();
        this.getTmplIds();
        Promise.all([ P1, P2 ]).then(function(values) {
            _this.getOrder();
            //预付单
                });
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        var _this = this;
        var P1 = _this.getMyLeaderInfo();
        var P2 = _this.getRecieverInfo();
        var pageRoute = _this.__displayReporter.showReferpagepath;
        Promise.all([ P1, P2 ]).then(function(values) {
            if (pageRoute == "addressManagerPackage/pages/addressList/addressList.html") {
                _this.getOrder();
                //预付单
                        }
        });
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    getOrder: function() {
        let _this = this;
        var {items: items, leader_id: leader_id, integal_use: integal_use, operation: operation, operation_type: operation_type, proceed_id: proceed_id, seckill_session_id: seckill_session_id, group_solit_id: group_solit_id, chose_delivery_channel: chose_delivery_channel, voucher_use: voucher_use, voucher_id: voucher_id, recieverInfo: recieverInfo} = _this.data;
        let position_x;
        if (recieverInfo.position) {
            position_x = recieverInfo.position.split(",");
        } else {
            position_x = [ "", "" ];
        }
        console.log(position_x);
        var params = {
            items: items,
            leader_id: leader_id,
            integal_use: integal_use,
            operation: operation,
            operation_type: operation_type,
            proceed_id: proceed_id,
            seckill_session_id: seckill_session_id,
            group_solit_id: group_solit_id,
            chose_delivery_channel: _this.data.chose_delivery_channel,
            voucher_use: voucher_use,
            voucher_id: voucher_id,
            address_name: recieverInfo.city,
            address_detail: recieverInfo.area,
            receiver_name: recieverInfo.receiverName,
            receiver_phone: recieverInfo.phone,
            lat: position_x[1],
            lng: position_x[0],
            wwb_street_id: recieverInfo.wwb_street_id,
            lottery_prize_id: _this.data.lottery_prize_id
        };
        //  console.log('大巴快速打开的嘎扣税的');
        // console.log(_this.data);
                return new Promise((resolve, reject) => {
            console.log(recieverInfo);
            common.request({
                endpoint: "Order/common/advance-order",
                method: "post",
                data: params,
                success: res => {
                    if (res.code == 1007) {
                        wx.showModal({
                            title: "提示",
                            content: "地址未获取到经纬度坐标，请重新获取",
                            complete: function(res) {
                                wx.navigateTo({
                                    url: "/addressManagerPackage/pages/addressList/addressList"
                                });
                            }
                        });
                        return;
                    }
                    if (res.code == 1008) {
                        wx.showModal({
                            title: "提示",
                            content: "您购买的商品必须完善街道才能下单",
                            complete: function(res1) {
                                console.log(222);
                                if (res1.cancel) {} else {
                                    wx.navigateTo({
                                        url: "/addressManagerPackage/pages/addressList/addressList"
                                    });
                                }
                            }
                        });
                        return;
                    }
                    var detail = res.extra;
                    //支付方式
                                        _this.setPayWay(detail);
                    //红包
                                        _this.setVoucher(detail);
                    var delivery_types = detail.delivery_types;
                    delivery_types.forEach(item => {
                        if (item.is_chose == 1) {
                            chose_delivery_channel = item.delivery_channel;
                        }
                    });
                    _this.setData({
                        actually_paid: detail.actually_paid,
                        //实际支付金额
                        hidden_discount: detail.hidden_discount,
                        //实际总优惠
                        delivery_types: detail.delivery_types,
                        //配送方式
                        chose_delivery_channel: chose_delivery_channel,
                        //默认起始配送方式
                        platPro: detail.common_products,
                        //平台商品
                        expressPro: detail.express_products,
                        //快递商品
                        express_delivery: detail.express_delivery,
                        //快递费
                        delivery_fee_info: detail.delivery_fee_info,
                        //配送费详情
                        voucher: detail.voucher,
                        //红包
                        integral: detail.integral,
                        //积分
                        full_discount: detail.full_discount,
                        //满减
                        balance: detail.balance,
                        //余额
                        special_funds: detail.special_funds,
                        //专项资金
                        integal_use: _this.data.integal_use,
                        voucher_use: detail.voucher.voucher_display == 1 && detail.voucher.use_voucher_id ? true : false,
                        voucher_id: detail.voucher.use_voucher_id,
                        //使用红包的id
                        hidden_products_paid: detail.hidden_products_paid,
                        //不含配送费的实际商品支付金额
                        current_common_total: detail.current_common_total,
                        //除快递商品以外，商品现价总价（会员折后）
                        total_discount: detail.total_discount,
                        //总优惠
                        hidden_discount: detail.hidden_discount,
                        //实际总优惠
                        enjoy_free_shipping: detail.enjoy_free_shipping,
                        //会员是否享受包邮权益
                        starting_info: detail.starting_info,
                        //起送价详情
                        current_express_total: detail.current_express_total,
                        //快递商品的现价总价（会员折后）
                        starting_info: detail.starting_info,
                        //起送设置
                        defferNum: detail.starting_info.is_achieve ? "立即支付" : `差${detail.starting_info.starting_difference}元起购`,
                        isPayStatus: detail.starting_info.is_achieve,
                        delivery_time_range: detail.delivery_time_range,
                        //平台送达时间范围
                        rider_delivery_range: detail.rider_time_range,
                        //骑手配送开启与时间范围
                        delivery_rangeArr: [ detail.delivery_fee_info.rider_day, detail.delivery_fee_info.rider_time ],
                        channel: detail.channel
                    });
                    let special_custom_name_flag = false;
                    if (_this.data.features.specFund == 1) {
                        let special_custom_name_flag_a = true;
                        let special_custom_name_flag_b = true;
                        _this.data.platPro.forEach((item, index) => {
                            if (!item.is_special_funds) {
                                special_custom_name_flag_a = false;
                            }
                        });
                        _this.data.expressPro.forEach((item, index) => {
                            if (!item.is_special_funds) {
                                special_custom_name_flag_b = false;
                            }
                        });
                        // console.log(special_custom_name_flag_a)
                        // console.log(special_custom_name_flag_b)
                                                if (special_custom_name_flag_a && special_custom_name_flag_b) {
                            _this.setData({
                                special_custom_name_flag: true
                            });
                        } else {
                            _this.setData({
                                special_custom_name_flag: false
                            });
                        }
                    } else {
                        _this.setData({
                            special_custom_name_flag: false
                        });
                    }
                    let money_xx = _this.data.order_start * 100 - _this.data.hidden_products_paid * 100;
                    _this.setData({
                        money_xx: money_xx / 100
                    });
                    let rider_day = [];
                    let rider_time = [];
                    let rider_time_range_new = [];
                    detail.rider_time_range.time_range.forEach((item, index) => {
                        rider_day.push(item.day);
                        rider_time.push(item.time);
                    });
                    //骑手配送时间
                                        _this.setData({
                        rider_time_range_new: [ rider_day, rider_time[0] ],
                        //默认显示第一个
                        rider_time: rider_time,
                        rider_day: rider_day
                    });
                    let platform_day = [];
                    let platform_time = [];
                    let platform_time_range_new = [];
                    detail.delivery_time_range.time_range.forEach((item, index) => {
                        platform_day.push(item.day);
                        platform_time.push(item.time);
                    });
                    //平台配送时间
                                        _this.setData({
                        delivery_time_range_new: [ platform_day, platform_time[0] ],
                        //默认显示第一个
                        platform_time: platform_time,
                        platform_day: platform_day
                    });
                    if (_this.data.delivery_time_range.time_range_switch == 1) {
                        var time_range = detail.delivery_time_range.time_range;
                        var delivery_rangeArr_Reach = [ time_range.day, time_range.time ];
                        _this.setData({
                            delivery_rangeArr_Reach: delivery_rangeArr_Reach
                        });
                    }
                    if (!_this.data.leader_id && _this.data.platPro.length) {
                        if (_this.data.leader_change == "1") {
                            wx.showModal({
                                title: "提示",
                                content: "您还没有选择" + _this.data.leaderName + "，请先选择" + _this.data.leaderName + "后再下单",
                                showCancel: false,
                                success(res) {
                                    if (res.confirm) {
                                        wx.redirectTo({
                                            url: "/pages/nearby_group2/nearby_group2"
                                        });
                                    }
                                }
                            });
                        } else {
                            wx.showModal({
                                title: "提示",
                                content: "您还没有" + _this.data.leaderName + "，请点击" + _this.data.leaderName + "转发的小程序后下单！",
                                showCancel: false,
                                success(res) {
                                    if (res.confirm) {
                                        wx.reLaunch({
                                            url: "/pages/index/index"
                                        });
                                    }
                                }
                            });
                        }
                    }
                    resolve();
                },
                fail(res) {
                    if (res.code == 1007) {
                        wx.showModal({
                            title: "提示",
                            content: "地址未获取到经纬度坐标，请重新获取",
                            success: function(res) {
                                wx.navigateTo({
                                    url: "/addressManagerPackage/pages/addressList/addressList"
                                });
                            },
                            fail: res => {}
                        });
                        return;
                    }
                    if (res.code == 1008) {
                        wx.showModal({
                            title: "提示",
                            content: "您购买的商品必须完善街道才能下单",
                            complete: function(res1) {
                                console.log(222);
                                if (res1.cancel) {} else {
                                    wx.navigateTo({
                                        url: "/addressManagerPackage/pages/addressList/addressList"
                                    });
                                }
                            }
                        });
                        return;
                    }
                    if (res.code != 0) {
                        wx.showModal({
                            title: "提示",
                            content: res.message,
                            complete: function(res) {
                                wx.navigateBack();
                            }
                        });
                        return;
                    }
                    resolve();
                }
            });
        });
    },
    bindColumnChangeRider(e) {
        let that = this;
        if (e.detail.column == 0) {
            that.setData({
                rider_time_range_new: [ that.data.rider_day, that.data.rider_time[e.detail.value] ]
            });
        }
    },
    bindColumnChangePlatform(e) {
        let that = this;
        if (e.detail.column == 0) {
            that.setData({
                delivery_time_range_new: [ that.data.platform_day, that.data.platform_time[e.detail.value] ]
            });
        }
    },
    bindMultiPickerChangeReach: function(e) {
        var delivery_rangeArr = this.data.delivery_time_range_new;
        this.setData({
            multiIndex: e.detail.value
        });
        var multiIndex = this.data.multiIndex;
        var reach_time = delivery_rangeArr[0][multiIndex[0]] + " " + delivery_rangeArr[1][multiIndex[1]];
        var date_rang_time = new Date(reach_time + ":00").getTime();
        var now_date = new Date().getTime();
        if (date_rang_time < now_date) {
            wx.showToast({
                icon: "none",
                title: "选择时间必须大于当前时间"
            });
            return false;
        } else {
            this.setData({
                reach_time: reach_time
            });
        }
    },
    bindMultiPickerColumnChange(e) {
        var current = e.detail.value;
        var multiIndex = this.data.multiIndex;
        multiIndex = [ multiIndex[0], current ];
        var delivery_rangeArr = this.data.delivery_rangeArr;
        var reach_time = delivery_rangeArr[0][multiIndex[0]] + " " + delivery_rangeArr[1][multiIndex[1]];
        var date_rang_time = new Date(reach_time + ":00").getTime();
        var now_date = new Date().getTime();
        if (date_rang_time < now_date) {
            wx.showToast({
                icon: "none",
                title: "选择时间必须大于当前时间"
            });
            return false;
        } else {
            this.setData({
                multiIndex: multiIndex,
                reach_time: reach_time
            });
        }
    },
    bindMultiPickerChange: function(e) {
        console.log(e);
        var delivery_rangeArr = this.data.rider_time_range_new;
        this.setData({
            multiIndex: e.detail.value
        });
        var multiIndex = this.data.multiIndex;
        var user_est_time = delivery_rangeArr[0][multiIndex[0]] + " " + delivery_rangeArr[1][multiIndex[1]];
        var date_rang_time = new Date(user_est_time + ":00").getTime();
        var now_date = new Date().getTime();
        if (date_rang_time < now_date) {
            wx.showToast({
                icon: "none",
                title: "选择时间必须大于当前时间"
            });
            return false;
        } else {
            this.setData({
                reach_time: user_est_time
            });
        }
    },
    //选择支付方式
    radioChange: function(e) {
        this.setData({
            payment_channel: e.detail.value
        });
    },
    //选择红包
    choose_discount: function(e) {
        var id = e.currentTarget.dataset.id;
        if (this.data.voucher_id == id) {
            this.setData({
                voucher_id: null,
                voucher_use: false
            });
        } else {
            this.setData({
                voucher_id: id,
                voucher_use: true
            });
        }
        this.getOrder();
    },
    //切换配送方式
    chooseMethod: function(e) {
        this.setData({
            confirm_lead: 0
        });
        var _this = this;
        var type = e.currentTarget.dataset.type;
        _this.setData({
            chose_delivery_channel: type
        });
        let {delivery_fee_info: delivery_fee_info, enjoy_free_shipping: enjoy_free_shipping, current_common_total: current_common_total, current_express_total: current_express_total, chose_delivery_channel: chose_delivery_channel, actually_paid: actually_paid} = _this.data;
        // chose_delivery_channel = e.currentTarget.dataset.type;
        // _this.setData({
        //   chose_delivery_channel:chose_delivery_channel
        // })
                var transPay = 0;
        //切换之前的配送费
                if (chose_delivery_channel == 1) {
            //自提配送费-无配送费  
            _this.getOrder();
        } else if (chose_delivery_channel == 2 && !_this.enjoy_free_shipping) {
            //团长配送费-或者享受会员免配送
            _this.getOrder();
            transPay = delivery_fee_info.leader_delivery;
        } else if (chose_delivery_channel == 3) {
            //平台配送费
            _this.getOrder();
            transPay = delivery_fee_info.esb_delivery;
        } else if (chose_delivery_channel == 5) {
            //骑手配送费
            _this.getOrder();
            transPay = delivery_fee_info.rider_delivery;
        } else if (chose_delivery_channel == 6) {
            //同城配送费
            _this.getOrder();
            transPay = delivery_fee_info.distribution_delivery;
            console.log(transPay);
        }
        console.log(_this.data.chose_delivery_channel);
        if (_this.data.chose_delivery_channel == 1) {
            //到点自提-不含配送费
            _this.setData({
                actually_paid: parseFloat(parseFloat(actually_paid) - parseFloat(transPay)).toFixed(2)
            });
        } else if (_this.data.chose_delivery_channel == 2) {
            //团长配送-计算配送费 是否享受会员免配送费
            if (this.data.enjoy_free_shipping || parseFloat(current_common_total) >= parseFloat(delivery_fee_info.free_leader_delivery_condition) && delivery_fee_info.free_leader_delivery_switch == 1) {
                //达到满额包邮
                _this.setData({
                    actually_paid: parseFloat(parseFloat(actually_paid) - parseFloat(transPay)).toFixed(2),
                    ["delivery_fee_info.leader_delivery"]: 0
                });
            } else {
                _this.setData({
                    actually_paid: parseFloat(parseFloat(actually_paid) - parseFloat(transPay) + parseFloat(delivery_fee_info.default_leader_delivery)).toFixed(2),
                    ["delivery_fee_info.leader_delivery"]: parseFloat(delivery_fee_info.default_leader_delivery).toFixed(2)
                });
            }
        } else if (_this.data.chose_delivery_channel == 3) {
            //平台配送-计算配送费 是否享受会员免配送费
            if (parseFloat(current_common_total) >= parseFloat(delivery_fee_info.free_esb_delivery_condition) && delivery_fee_info.free_esb_delivery_switch == 1) {
                //达到满额包邮
                _this.setData({
                    actually_paid: parseFloat(parseFloat(actually_paid) - parseFloat(transPay)).toFixed(2),
                    ["delivery_fee_info.esb_delivery"]: 0
                });
            } else {
                _this.setData({
                    actually_paid: parseFloat(parseFloat(actually_paid) - parseFloat(transPay) + parseFloat(delivery_fee_info.default_esb_delivery)).toFixed(2),
                    ["delivery_fee_info.esb_delivery"]: parseFloat(delivery_fee_info.default_esb_delivery).toFixed(2)
                });
            }
        } else if (_this.data.chose_delivery_channel == 5) {
            //骑手配送
            _this.setData({
                actually_paid: parseFloat(parseFloat(actually_paid) - parseFloat(transPay) + parseFloat(delivery_fee_info.rider_delivery)).toFixed(2)
            });
        } else if (_this.data.chose_delivery_channel == 6) {
            //同城配送
            console.log(6666);
            if (_this.data.delivery_fee_info.distribution_fee_type == 0) {
                //第三方配送由后台设置决定
                console.log(111);
                if (parseFloat(current_common_total) >= parseFloat(delivery_fee_info.distribution_delivery) && delivery_fee_info.free_esb_delivery_switch == 1) {
                    //达到满额包邮
                    _this.setData({
                        actually_paid: parseFloat(parseFloat(actually_paid) - parseFloat(transPay)).toFixed(2)
                    });
                } else {
                    console.log(222);
                    _this.setData({
                        actually_paid: parseFloat(parseFloat(actually_paid) - parseFloat(transPay) + parseFloat(delivery_fee_info.distribution_delivery)).toFixed(2)
                    });
                }
            } else {
                console.log(333);
                _this.setData({
                    actually_paid: parseFloat(parseFloat(actually_paid) - parseFloat(transPay) + parseFloat(delivery_fee_info.distribution_delivery)).toFixed(2)
                });
            }
        }
    },
    //设置已红包
    setVoucher: function(detail) {
        var _this = this;
        if (!detail.voucher.voucher_info) {
            return false;
        }
        var usable = detail.voucher.voucher_info.usable;
        if (detail.voucher.voucher_display == 1 && detail.voucher.use_voucher_id) {
            usable.forEach(item => {
                if (item.id == detail.voucher.use_voucher_id) {
                    _this.setData({
                        voucher_use_item: item
                    });
                }
            });
        }
    },
    //设置支付方式
    setPayWay: function(detail) {
        var _this = this;
        var payWayList1 = _this.data.payWayList1;
        var payWayList = [];
        payWayList1.forEach(item => {
            if (detail.balance.balance_display == 1 && item.payWayName == "余额" || item.payWayName == "微信支付" || detail.cash_on_delivery.display == 1 && item.payWayName == "货到付款" || detail.special_funds.special_funds_display == 1 && item.payWayName == "专项资金") {
                payWayList.push(item);
            }
        });
        var balanceNumTip = "";
        var specFundNumTip = "";
        var payment_channel = 1;
        //支付方式
                payWayList.forEach(item => {
            if (item.payWayName == "余额" && parseFloat(detail.balance.my_balance) >= parseFloat(detail.actually_paid)) {
                balanceNumTip = "（余额：￥" + detail.balance.my_balance + "）";
                payment_channel = 2;
            }
            if (item.payWayName == "余额" && parseFloat(detail.balance.my_balance) < parseFloat(detail.actually_paid)) {
                balanceNumTip = "（余额不足：￥" + detail.balance.my_balance + "）";
                item.isDisabled = true;
            }
            if (item.payWayName == "专项资金" && parseFloat(detail.special_funds.my_special_funds) >= parseFloat(detail.actually_paid)) {
                specFundNumTip = "（" + _this.data.special_custom_name + "：￥" + detail.special_funds.my_special_funds + "）";
            }
            if (item.payWayName == "专项资金" && parseFloat(detail.special_funds.my_special_funds) < parseFloat(detail.actually_paid)) {
                specFundNumTip = "（" + _this.data.special_custom_name + "不足：￥" + detail.special_funds.my_special_funds + "）";
                item.isDisabled = true;
            }
        });
        _this.setData({
            payWayList: payWayList,
            //支付方式
            payment_channel: payment_channel,
            balanceNumTip: balanceNumTip,
            //余额提示
            specFundNumTip: specFundNumTip
        });
    },
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarTitle({
                    title: res.extra.title
                });
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                that.setData({
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    apptitle: res.extra.title,
                    style: res.extra.style,
                    leader_change: res.extra.l_change,
                    leader_express: res.extra.l_exapp_basepress,
                    rp_name: res.extra.rp_name,
                    order_start: res.extra.order_start,
                    order_start_switch: res.extra.order_start_switch,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    ["goodsListStyle.leaderName"]: res.extra.leader_title ? res.extra.leader_title : "团长",
                    communityName: res.extra.community_title ? res.extra.community_title : "社区",
                    leader_address_on: res.extra.leader_address_on,
                    integral_status: res.extra.integral_status,
                    need_order_location: res.extra.need_order_location,
                    special_custom_name: res.extra.special_custom_name
                });
                //处理模块开关
                                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    features: features
                });
                //设置模块颜色
                                var componentStyle = that.data.componentStyle;
                that.setData({
                    componentStyle: {
                        ...componentStyle,
                        color_main: !res.extra.color_main ? "#FE513B" : res.extra.color_main,
                        color_minor: !res.extra.color_minor ? "#FE513B" : res.extra.color_minor
                    }
                });
            }
        });
    },
    //获取团长配送
    getMyLeaderInfo: function() {
        var _this = this;
        return new Promise(function(resolve, reject) {
            common.request({
                endpoint: "leader/myleaderinfo",
                method: "post",
                data: {
                    openid: wx.getStorageSync("user").openid
                },
                success: res => {
                    var leaderInfo = {
                        teamName: res.extra.title,
                        //团名
                        leaderName: res.extra.name,
                        //团长名称
                        phone: res.extra.phone,
                        //电话
                        address: res.extra.other,
                        //自提点
                        url: ""
                    };
                    _this.setData({
                        myleaderinfo: res.extra,
                        leader_id: res.extra.leader_id,
                        leaderInfo: leaderInfo
                    });
                    resolve("A");
                }
            });
        });
    },
    close_discount: function() {
        this.setData({
            discount_alert: 0
        });
    },
    show_discount: function() {
        var that = this;
        that.setData({
            discount_alert: 1
        });
    },
    choose_label: function(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        that.setData({
            discount_label: id
        });
    },
    confirm_discount: function() {
        this.setData({
            discount_alert: 0
        });
    },
    getInfo: function(type) {
        var openid = wx.getStorageSync("user").openid;
        var that = this;
        common.request({
            endpoint: "member/myinfo",
            method: "post",
            data: {
                openid: openid
            },
            header: {
                "content-type": "application/json"
            },
            success(res) {
                console.log(res);
                var formConfig = that.data.formConfig;
                if (type == 1) {
                    formConfig.forEach((item, index) => {
                        switch (item.formData.name) {
                          case "name":
                            if (res.extra.name) {
                                item.formData.value = res.extra.name;
                            } else {
                                item.formData.value = "";
                            }
                            break;

                          case "phone":
                            if (res.extra.name) {
                                item.formData.value = res.extra.phone;
                            } else {
                                item.formData.value = "";
                            }
                            break;

                          case "city":
                            if (res.extra.name) {
                                item.formData.value = res.extra.address_name;
                            } else {
                                item.formData.value = [];
                            }
                            break;

                          case "house_number":
                            if (res.extra.name) {
                                item.formData.value = res.extra.address_other;
                            } else {
                                item.formData.value = "";
                            }
                            break;
                        }
                    });
                }
                that.setData({
                    name: res.extra.name,
                    phone: res.extra.phone,
                    house_number: res.extra.address_other,
                    remark: res.extra.remark,
                    formConfig: formConfig,
                    myInfo: res.extra
                });
            }
        });
    },
    getRecieverInfo() {
        let that = this;
        return new Promise((resolve, reject) => {
            var reciever = app.globalData.reciever;
            if (reciever) {
                that.setData({
                    recieverInfo: {
                        ...reciever,
                        url: "/addressManagerPackage/pages/addressList/addressList"
                    }
                });
                console.log(333);
                resolve();
            } else {
                common.request({
                    endpoint: "member/def_address",
                    method: "post",
                    data: {},
                    success(res) {
                        console.log(res, "reciever");
                        var data = res.extra;
                        if (data) {
                            var recieverInfo = {
                                receiverName: data.name,
                                //收货人名称
                                phone: data.phone,
                                //电话
                                address: data.city + " " + data.area,
                                //收货地址
                                city: data.city,
                                area: data.area,
                                position: data.position,
                                lng: data.position ? data.position.split(",")[0] : "",
                                lat: data.position ? data.position.split(",")[1] : "",
                                wwb_street_id: data.wwb_street_id,
                                url: "/addressManagerPackage/pages/addressList/addressList"
                            };
                            app.globalData.reciever = recieverInfo;
                            that.setData({
                                recieverInfo: recieverInfo
                            });
                            resolve();
                        } else {
                            var recieverInfo = {
                                url: "/addressManagerPackage/pages/addressList/addressList"
                            };
                            that.setData({
                                recieverInfo: recieverInfo
                            });
                            resolve();
                        }
                    },
                    fail(err) {
                        reject();
                    }
                });
            }
        });
    },
    //获取tmplIds
    getTmplIds: function() {
        let that = this;
        const version = wx.getSystemInfoSync().SDKVersion;
        //console.log(version);
                if (util.compareVersion(version, "2.8.2") < 0) {
            that.setData({
                tmplIds: [],
                subscribeMessage: false
            });
            return;
        }
        common.request({
            endpoint: "set/template_get",
            method: "post",
            data: {},
            header: {
                "content-type": "application/json"
            },
            success: res => {
                console.log(res);
                let tmplIds = [];
                let subscribeMessage = true;
                res.extra.map(v => {
                    if ((v.type == "23" || v.type == "29" || v.type == "21") && v.status == "1") {
                        tmplIds.push(v.template_id);
                    }
                });
                if (!tmplIds.length) {
                    subscribeMessage = false;
                }
                that.setData({
                    tmplIds: tmplIds,
                    subscribeMessage: subscribeMessage
                });
            }
        });
    },
    recordValue: function(e) {
        let that = this;
        let key = e.currentTarget.dataset.name;
        that.setData({
            [key]: e.detail.value
        });
    },
    /**
   * 记录收件人修改
   */
    recordValue_info: function(e) {
        let that = this;
        let key = "recieverInfo." + e.detail.key;
        let value = e.detail.value;
        that.setData({
            [key]: value
        });
    },
    //团长切换
    leader_change: function(e) {
        var address = e.currentTarget.dataset.address;
        var is_leader = wx.getStorageSync("my_leader").is_leader;
        if (is_leader == 1) {
            wx.showModal({
                title: "提示",
                content: "您自己是" + that.data.leaderName + "不能切换" + that.data.leaderName + "！"
            });
        }
        if (this.data.leader_change == 1 && is_leader != 1) {
            wx.navigateTo({
                url: "/pages/nearby_group2/nearby_group2"
            });
        }
    },
    confirmInfo: function() {
        let that = this;
        common.getUserInfoNew({
            success() {
                if (that.data.need_order_location == 1) {
                    //需要定位
                    if (that.data.chose_delivery_channel == 3 && !that.data.recieverInfo.lat) {
                        //平台配送定位
                        wx.showModal({
                            title: "提示",
                            content: "平台配送请重新编辑地址里的定位信息！",
                            success(res) {
                                if (res.confirm) {
                                    wx.navigateTo({
                                        url: "/addressManagerPackage/pages/addressList/addressList"
                                    });
                                }
                            }
                        });
                        return;
                    }
                    if (that.data.chose_delivery_channel == 5 && !that.data.recieverInfo.lat && !that.data.expressPro.length) {
                        //骑手配送必须定位位置
                        wx.showModal({
                            title: "提示",
                            content: "骑手配送请重新编辑地址里的定位信息!",
                            success(res) {
                                if (res.confirm) {
                                    wx.navigateTo({
                                        url: "/addressManagerPackage/pages/addressList/addressList"
                                    });
                                }
                            }
                        });
                        return false;
                    }
                    if (!that.data.recieverInfo.area && that.data.chose_delivery_channel != 1 || !that.data.recieverInfo.area && that.data.expressPro.length) {
                        //除快递和自提不用地址
                        wx.showModal({
                            title: "提示",
                            content: "暂无地址信息,请先选择地址！",
                            success(res) {
                                if (res.confirm) {
                                    wx.navigateTo({
                                        url: "/addressManagerPackage/pages/addressList/addressList"
                                    });
                                }
                            }
                        });
                        return false;
                    }
                }
                if (that.data.chose_delivery_channel == 5 && !that.data.reach_time && that.data.rider_delivery_range.time_range_switch == 1) {
                    //骑手配送必须选择送达时间（在开启送达时间的时候）
                    wx.showModal({
                        title: "提示",
                        content: "骑手配送请选择送达时间",
                        success(res) {}
                    });
                    return false;
                }
                if (that.data.delivery_time_range.time_range_switch == 1 && that.data.chose_delivery_channel == 3) {
                    console.log();
                    if (!that.data.reach_time) {
                        wx.showModal({
                            title: "提示",
                            content: "请选择送达时间",
                            success(res) {}
                        });
                        return false;
                    }
                }
                if (that.data.subscribeMessage) {
                    wx.requestSubscribeMessage({
                        tmplIds: that.data.tmplIds,
                        success(res) {},
                        fail(err) {
                            console.log(err);
                        },
                        complete() {
                            that.confirmInfo_ch();
                        }
                    });
                    // }
                                } else {
                    that.confirmInfo_ch();
                }
            }
        });
    },
    confirmInfo_ch() {
        var that = this;
        var payButtonDisabled = that.data.payButtonDisabled;
        if (!this.data.isPayStatus || payButtonDisabled) {
            //不满足满减条件或按钮禁用
            return false;
        }
        that.setData({
            payButtonDisabled: true
        });
        //验证收件人信息
                var recieverInfo = that.data.recieverInfo;
        if (!recieverInfo.receiverName) {
            wx.showModal({
                title: "提示",
                content: "请选择收件人",
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            payButtonDisabled: false
                        });
                    }
                }
            });
            return false;
        }
        if (!/^1[23456789]\d{9}$/.test(recieverInfo.phone) && that.data.chose_delivery_channel == 1) {
            wx.showModal({
                title: "提示",
                content: "请输入正确的手机号码！",
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            payButtonDisabled: false
                        });
                    }
                }
            });
            return false;
        }
        that.setData({
            payment_status: 0
        });
        if (that.data.chose_delivery_channel == 4 || !that.data.platPro || that.data.platPro.length == 0) {
            that.confirm_order_preopay();
        } else {
            that.setData({
                confirm_lead: 1
            });
        }
        // this.filterTeamer();
        },
    integralChange: function() {
        this.setData({
            integal_use: !this.data.integal_use
        });
        this.getOrder();
    },
    /**
   * 
   * 筛选团长专属
   * 
   */
    filterTeamer() {
        let that = this;
        var items = that.data.items;
        var ids = [];
        items.forEach(item => {
            ids.push(item.sku_id);
        });
        var params = {
            data: ids
        };
        if (that.data.group_solit_id) {
            params["group_id"] = that.data.group_solit_id;
        }
        var order_goods = that.data.platPro.concat(that.data.expressPro);
        console.log(order_goods, "dddd");
        common.request({
            endpoint: "product/cart_num",
            method: "post",
            data: params,
            success: res => {
                console.log(res, "good");
                //var stock=res.extra.default.concat(res.extra.express);
                //判断平台商品是否是团长售卖商品
                //var stock = res.extra.default;
                                var showTip = "您所购买的";
                var num = 0;
                var stock;
                var defaultPro = res.extra.default;
                var express = res.extra.express;
                //处理数据
                                if (defaultPro.length > 0) {
                    defaultPro.forEach((item, index) => {
                        item.proType = 0;
                    });
                }
                if (express.length > 0) {
                    express.forEach((item, index) => {
                        item.proType = 1;
                    });
                }
                stock = defaultPro.concat(express);
                stock.forEach((item, index) => {
                    if (item.if == 0 && item.proType == 0) {
                        num++;
                        var str = "【" + order_goods[index].name + "】";
                        showTip += str;
                    }
                });
                showTip += "不属于该" + that.data.leaderName;
                //that.confirm_order();
                //团长专属商品
                                if (num > 0) {
                    //有不属于该团长的商品，
                    wx.showModal({
                        title: "提示",
                        content: showTip,
                        showCancel: false,
                        success() {
                            //返回前一页
                            wx.navigateBack();
                        }
                    });
                } else {
                    //没有不属于该团长的商品
                    //判断弹窗,快递配送时候不显示团长-显示支付
                    if (that.data.chose_delivery_channel == 4 || !that.data.platPro || that.data.platPro.length == 0) {
                        that.confirm_order_preopay();
                    } else {
                        that.setData({
                            confirm_lead: 1
                        });
                    }
                }
            }
        });
    },
    close_confirm: function() {
        this.setData({
            confirm_lead: 0,
            payButtonDisabled: false
        });
    },
    confirm_order_preopay: function() {
        var that = this;
        var payment_channel = that.data.payment_channel;
        console.log(payment_channel);
        var actually_paid = that.data.actually_paid;
        if (payment_channel == 2) {
            //余额
            that.setData({
                confirm_lead: 0,
                payName: "余额",
                balance_confirm: 1
            });
        } else if (payment_channel == 1) {
            that.confirm_order();
        } else if (payment_channel == 3) {
            that.setData({
                confirm_lead: 0,
                payName: "专项资金",
                balance_confirm: 1
            });
        } else if (payment_channel == 4) {
            that.setData({
                confirm_lead: 0,
                payName: "货到付款",
                balance_confirm: 1
            });
        }
    },
    confirm_order: common.throttle(function() {
        var _this = this;
        var cart_storage = wx.getStorageSync("cart");
        var cart = [];
        var cart_count = "";
        wx.showLoading({
            title: "订单支付中..."
        });
        var {items: items, leader_id: leader_id, voucher_use: voucher_use, voucher_id: voucher_id, operation: operation, operation_type: operation_type, proceed_id: proceed_id, seckill_session_id: seckill_session_id, group_solit_id: group_solit_id, chose_delivery_channel: chose_delivery_channel, integal_use: integal_use, recieverInfo: recieverInfo, chose_delivery_channel: chose_delivery_channel, remark: remark, payment_channel: payment_channel, reach_time: reach_time} = _this.data;
        var params = {
            items: items,
            leader_id: leader_id,
            voucher_use: voucher_use,
            voucher_id: voucher_id,
            operation: operation,
            operation_type: operation_type,
            proceed_id: proceed_id,
            seckill_session_id: seckill_session_id,
            group_solit_id: group_solit_id,
            chose_delivery_channel: chose_delivery_channel,
            integal_use: integal_use,
            address_name: recieverInfo.city,
            address_detail: recieverInfo.area,
            receiver_name: recieverInfo.receiverName,
            receiver_phone: recieverInfo.phone,
            lat: recieverInfo.city,
            lat: recieverInfo.lat,
            lng: recieverInfo.lng,
            chose_delivery_channel: chose_delivery_channel,
            remark: remark,
            payment_channel: payment_channel,
            reach_time: reach_time,
            source_cart: _this.data.come,
            wwb_street_id: recieverInfo.wwb_street_id,
            lottery_prize_id: _this.data.lottery_prize_id
        };
        common.request({
            endpoint: "Order/common/place-order",
            method: "post",
            data: params,
            success: res => {
                wx.hideLoading();
                if (res.code == 1002) {
                    wx.showModal({
                        title: "提示",
                        content: res.message,
                        success: function(res1) {
                            console.log(2);
                            if (res1.cancel) {} else {
                                wx.navigateTo({
                                    url: "/addressManagerPackage/pages/addressList/addressList"
                                });
                            }
                        }
                    });
                    return;
                }
                if (res.code == 1008) {
                    wx.showModal({
                        title: "提示",
                        content: "您购买的商品必须完善街道才能下单",
                        success: function(res1) {
                            console.log(2);
                            if (res1.cancel) {} else {
                                wx.navigateTo({
                                    url: "/addressManagerPackage/pages/addressList/addressList"
                                });
                            }
                        }
                    });
                    return;
                }
                if (_this.data.status == 1) {
                    for (var i = 0; i < cart_storage.length; i++) {
                        if (cart_storage[i]["select"] == 0) {
                            cart.push(cart_storage[i]);
                            cart_count += cart_storage[i]["count"];
                        }
                    }
                    wx.setStorage({
                        key: "cart",
                        data: cart
                    });
                    wx.setStorage({
                        key: "cart_count",
                        data: cart_count
                    });
                }
                var trade_no = res.extra.trade_no;
                _this.setData({
                    trade_no: trade_no
                });
                _this.payWay(res.extra, trade_no);
            },
            fail(err) {
                wx.hideLoading();
                if (err.code == 1008) {
                    wx.showModal({
                        title: "提示",
                        content: "您购买的商品必须完善街道才能下单",
                        success: function(res1) {
                            console.log(222);
                            if (res1.cancel) {} else {
                                wx.navigateTo({
                                    url: "/addressManagerPackage/pages/addressList/addressList"
                                });
                            }
                        }
                    });
                    return;
                }
                wx.showModal({
                    title: "提示",
                    content: err.message
                });
            }
        });
    }, 3e3),
    close_balance_confirm() {
        this.setData({
            balance_confirm: 0,
            payButtonDisabled: false
        });
    },
    /**
   * 
   * 支付方式
   * 
   */
    payWay(res, trade_no) {
        let that = this;
        var payment_channel = that.data.payment_channel;
        if (payment_channel == 2 || payment_channel == 3 || payment_channel == 4) {
            //余额
            that.confirm_balance();
        } else if (payment_channel == 1) {
            //微信支付
            this.setData({
                confirm_lead: 0
            });
            that.wexin_payWay(res, trade_no);
        }
    },
    confirm_balance() {
        var that = this;
        var trade_no = that.data.trade_no;
        var operation_type = that.data.operation_type;
        common.request({
            endpoint: "Order/common/sync-notify",
            method: "post",
            data: {
                order_no: trade_no
            },
            success: res => {
                that.setData({
                    balance_confirm: 0
                });
                if (operation_type == 1) {
                    setTimeout(function() {
                        wx.reLaunch({
                            url: "/spell/pages/spell_success/spell_success?order_num=" + trade_no + "&type=" + operation_type
                        });
                    }, 500);
                } else {
                    setTimeout(function() {
                        wx.reLaunch({
                            url: "/pages/order_confirm/order_confirm?order_no=" + trade_no
                        });
                    }, 500);
                }
                // setTimeout(function () {
                //   wx.reLaunch({
                //     url: '/pages/order_confirm/order_confirm?order_no=' + trade_no,
                //   })
                // }, 500);
                        },
            fail(err) {
                wx.showModal({
                    title: "提示",
                    content: err.message
                });
            }
        });
    },
    //微信支付
    wexin_payWay: function(res, order_no) {
        var _this = this;
        var trade_no = res.trade_no;
        if (Object.prototype.toString.call(res.pay) === "[object Array]" && !res.pay.length) {
            _this.syncNotify(trade_no);
        } else {
            wx.requestPayment({
                timeStamp: res.pay.timeStamp,
                nonceStr: res.pay.nonceStr,
                package: res.pay.package,
                signType: res.pay.signType,
                paySign: res.pay.paySign,
                success: function(res) {
                    console.log(res);
                    wx.showToast({
                        title: "支付成功",
                        icon: "success",
                        mask: true,
                        duration: 3e3,
                        success: function(res) {
                            wx.showToast({
                                title: "购买成功！",
                                icon: "success",
                                success: function() {
                                    _this.syncNotify(trade_no);
                                }
                            });
                        }
                    });
                },
                fail: function(res) {
                    wx.navigateBack({
                        success: function(e) {
                            let page = getCurrentPages().pop();
                            if (page == undefined || page == null) return;
                            page.onLoad();
                        }
                    });
                }
            });
        }
    },
    syncNotify: function(order_no) {
        var that = this;
        common.request({
            endpoint: "Order/common/sync-notify",
            method: "post",
            data: {
                order_no: order_no
            },
            success: res => {
                if (that.data.operation_type == 1) {
                    setTimeout(function() {
                        wx.reLaunch({
                            url: "/spell/pages/spell_success/spell_success?order_num=" + order_no + "&type=" + that.data.operation_type
                        });
                    }, 500);
                } else {
                    setTimeout(function() {
                        wx.reLaunch({
                            url: "/pages/order_confirm/order_confirm?order_no=" + order_no
                        });
                    }, 500);
                }
            },
            fail(err) {
                wx.showModal({
                    title: "提示",
                    content: err.message
                });
            }
        });
    }
});